<script setup lang="ts">
import {
  ColumnHeightOutlined,
  DeleteOutlined,
  DownOutlined,
  FormOutlined,
  PlusOutlined,
  ReloadOutlined,
  SettingOutlined,
  SolutionOutlined,
  UpOutlined,
  UserOutlined,
} from '@ant-design/icons-vue'
import type { MenuProps, PaginationProps, TableProps } from 'ant-design-vue'
import DeptTree from '~/pages/setting/components/dept-tree.vue'
import { UserTableColumns } from '~/pages/setting/datas/user-data.ts'
import { queryUserPageApi, removeUserByIdApi } from '~/api/setting/user.ts'
import type { UserReq, UserResp } from '~/api/setting/model/user.ts'
import type { Page } from '~/api/base/base-model.ts'

import { CommTablePagination, CommTableSize, CommTableSizeItems } from '~/components/comm-table/comm-table-data.ts'
import UserEditModal from '~/pages/setting/components/user-edit-modal.vue'

const message = useMessage()

const tableSize = shallowRef<string[]>(CommTableSize)
const sizeItems = CommTableSizeItems

const columns = UserTableColumns
const loading = shallowRef(false)

const pageSource = shallowRef<Page<UserResp>>()
const dataSource = shallowRef<UserResp[]>([])

const pagination = reactive<PaginationProps>({
  ...CommTablePagination,
  total: pageSource.value?.total,
  onChange(current, pageSize) {
    pagination.pageSize = pageSize
    pagination.current = current
    init()
  },
})

const expand = ref(false)
const formQuery = reactive<UserReq>({
  usernameByLike: undefined,
  realNameByLike: undefined,
  deptIds: [],
})

const dropdownVisible = ref(false)
const getCheckList = computed(() => columns.value.map(item => item.dataIndex))
const state = reactive({
  indeterminate: false,
  checkAll: true,
  checkList: getCheckList.value,
})

/**
 * 密度切换
 *
 */
const handleSizeChange: MenuProps['onClick'] = (e) => {
  tableSize.value[0] = e.key as string
}

/**
 * 过滤
 *
 */
function filterAction(value: string[]) {
  return columns.value.filter((item) => {
    return value.includes(item.dataIndex)
  })
}

// 备份columns
const filterColumns = ref(filterAction(getCheckList.value))

async function init() {
  if (loading.value) {
    return
  }
  loading.value = true
  try {
    pageSource.value = await queryUserPageApi({
      param: formQuery,
      current: pagination.current,
      size: pagination.pageSize,
    })
    dataSource.value = pageSource.value?.records ?? []
  } catch (e) {
    console.log(e)
  } finally {
    loading.value = false
  }
}

async function onItemSelect(node: string[]) {
  formQuery.deptIds = node
  await onSearch()
}

async function onSearch() {
  pagination.current = 1
  await init()
}

/**
 * 重置事件
 *
 */
function handleResetChange() {
  state.checkList = getCheckList.value
  filterColumns.value = filterAction(getCheckList.value)
}

async function onReset() {
  // 清空所有参数重新请求
  formQuery.usernameByLike = undefined
  formQuery.realNameByLike = undefined
  await init()
}

/**
 * 删除功能
 *
 * @param userResp
 */
async function onDeleteUser(userResp: UserResp) {
  const close = message.loading('删除中......')
  try {
    const userReq: UserReq = {
      id: userResp.id,
    }
    const isDel = await removeUserByIdApi(userReq)
    if (isDel) {
      await init()
    }
    message.success('删除成功')
  } catch (e) {
    console.log(e)
  } finally {
    close()
  }
}

const open = ref(false)
const optType = ref('create')
const userResp = ref<UserResp>({})

function openModalEditUser(opt: string, item?: UserResp) {
  open.value = true

  optType.value = opt
  if (opt === 'create') {
    userResp.value = {}
  } else {
    userResp.value = item || {}
  }
}

async function onSaveSuccess() {
  open.value = false
  await onSearch()
}

watch(
  () => state.checkList,
  (val) => {
    state.indeterminate = !!val.length && val.length < getCheckList.value.length
    state.checkAll = val.length === getCheckList.value.length
  },
)

onMounted(() => {
  init()
})
</script>

<template>
  <page-container>
    <a-row :gutter="24">
      <a-col class="gutter-row" :span="6">
        <DeptTree @on-item-select="onItemSelect" />
      </a-col>
      <a-col class="gutter-row" :span="18">
        <a-card mb-4>
          <a-form :label-col="{ span: 7 }" :model="formQuery">
            <a-row :gutter="[15, 0]">
              <a-col :span="8">
                <a-form-item name="username" label="用户账户">
                  <a-input v-model:value="formQuery.usernameByLike" placeholder="请输入用户账户" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item name="realName" label="用户名称">
                  <a-input v-model:value="formQuery.realNameByLike" placeholder="请输入用户名称" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :span="24" style="text-align: right">
              <a-col :span="24">
                <a-space flex justify-end w-full>
                  <a-button :loading="loading" type="primary" @click="onSearch">
                    查询
                  </a-button>
                  <a-button :loading="loading" @click="onReset">
                    重置
                  </a-button>
                  <a-button type="link" @click="expand = !expand">
                    {{ expand ? '收起' : '展开' }}
                    <UpOutlined v-if="expand" />
                    <DownOutlined v-else />
                  </a-button>
                </a-space>
              </a-col>
            </a-row>
          </a-form>
        </a-card>

        <a-card title="用户列表">
          <template #extra>
            <a-space size="middle">
              <a-button type="primary" @click="openModalEditUser('create')">
                <template #icon>
                  <PlusOutlined />
                </template>
                新增
              </a-button>
              <a-tooltip title="刷新">
                <ReloadOutlined @click="onSearch" />
              </a-tooltip>
              <a-tooltip title="密度">
                <a-dropdown trigger="click">
                  <ColumnHeightOutlined />
                  <template #overlay>
                    <a-menu v-model:selected-keys="tableSize" :items="sizeItems" @click="handleSizeChange" />
                  </template>
                </a-dropdown>
              </a-tooltip>
              <a-tooltip title="列设置">
                <a-dropdown v-model:open="dropdownVisible" trigger="click">
                  <SettingOutlined />
                  <template #overlay>
                    <a-card>
                      <template #extra>
                        <a-button type="link" @click="handleResetChange">
                          重置
                        </a-button>
                      </template>
                    </a-card>
                  </template>
                </a-dropdown>
              </a-tooltip>
            </a-space>
          </template>
          <a-table
            :loading="loading" :columns="filterColumns" :data-source="dataSource" :pagination="pagination"
            :size="tableSize[0] as TableProps['size']"
          >
            <template #bodyCell="scope">
              <template v-if="scope?.column?.dataIndex === 'indexNo'">
                {{ scope?.index + 1 }}
              </template>
              <template v-if="scope?.column?.dataIndex === 'iconFileUrl'">
                <div>
                  <a-avatar :size="32" :src="scope?.record?.iconFileUrl">
                    <template #icon>
                      <UserOutlined />
                    </template>
                  </a-avatar>
                </div>
              </template>
              <template v-if="scope?.column?.dataIndex === 'action'">
                <div>
                  <span>
                    <a><SolutionOutlined /></a>
                    <a-divider type="vertical" />
                    <a><FormOutlined @click="openModalEditUser('edit', scope?.record)" /></a>
                    <a-divider type="vertical" />
                    <a-popconfirm
                      v-if="dataSource.length"
                      title="确认删除?"
                      @confirm="onDeleteUser(scope?.record)"
                    >
                      <a><DeleteOutlined /></a>
                    </a-popconfirm>
                  </span>
                </div>
              </template>
            </template>
          </a-table>
        </a-card>
        <UserEditModal
          v-if="open" v-model:open="open"
          :opt-type="optType"
          :user-data="userResp"
          @on-save-success="onSaveSuccess"
        />
      </a-col>
    </a-row>
  </page-container>
</template>

<style lang="less" scoped>
</style>
